package com.imdroid.carac.activities;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.model.Destination;

/**
 * 常用地址设置界面
 * 
 */
public class NavigatorPointSetting extends BaseActivity {
	/**
	 * The hash map to indicate the controls
	 */
	private Map<View, String> addressButtonControls = new HashMap<View, String>();
	/**
	 * The hash map to indicate the controls
	 */
	private Map<View, String> addressTitleControls = new HashMap<View, String>();
	/**
	 * The hash map to indicate the controls
	 */
	private Map<View, Integer> addressTextIds = new HashMap<View, Integer>();

	private Map<String, ImageView> imageControls = new HashMap<String, ImageView>();

	/**
	 * The name of the address
	 */
	private String addressNames[] = { "home", "company", "common1", "common2",
			"common3", "common4", "common5", "common6" };

	/**
	 * The text view of the address
	 */
	private TextView tv_home, tv_company, tv_common1, tv_common2, tv_common3,
			tv_common4, tv_common5, tv_common6;
	/**
	 * The button of sending the address
	 */
	private Button btn_home, btn_company, btn_common1, btn_common2,
			btn_common3, btn_common4, btn_common5, btn_common6;

	private ImageView iv_home, iv_company, iv_common1, iv_common2, iv_common3,
			iv_common4, iv_common5, iv_common6;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.imdroid.carac.activities.BaseActivity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loc_navigator_points);

		// 初始化各控件
		tv_home = (TextView) findViewById(R.id.loc_tv_map_set_home);
		tv_company = (TextView) findViewById(R.id.loc_tv_map_set_company);
		tv_common1 = (TextView) findViewById(R.id.loc_tv_map_set_common1);
		tv_common2 = (TextView) findViewById(R.id.loc_tv_map_set_common2);
		tv_common3 = (TextView) findViewById(R.id.loc_tv_map_set_common3);
		tv_common4 = (TextView) findViewById(R.id.loc_tv_map_set_common4);
		tv_common5 = (TextView) findViewById(R.id.loc_tv_map_set_common5);
		tv_common6 = (TextView) findViewById(R.id.loc_tv_map_set_common6);

		btn_home = (Button) findViewById(R.id.loc_btn_map_set_home);
		btn_company = (Button) findViewById(R.id.loc_btn_map_set_company);
		btn_common1 = (Button) findViewById(R.id.loc_btn_map_set_common1);
		btn_common2 = (Button) findViewById(R.id.loc_btn_map_set_common2);
		btn_common3 = (Button) findViewById(R.id.loc_btn_map_set_common3);
		btn_common4 = (Button) findViewById(R.id.loc_btn_map_set_common4);
		btn_common5 = (Button) findViewById(R.id.loc_btn_map_set_common5);
		btn_common6 = (Button) findViewById(R.id.loc_btn_map_set_common6);

		iv_home = (ImageView) findViewById(R.id.loc_btn_map_set_home_img);
		iv_company = (ImageView) findViewById(R.id.loc_btn_map_set_company_img);
		iv_common1 = (ImageView) findViewById(R.id.loc_btn_map_set_common1_img);
		iv_common2 = (ImageView) findViewById(R.id.loc_btn_map_set_common2_img);
		iv_common3 = (ImageView) findViewById(R.id.loc_btn_map_set_common3_img);
		iv_common4 = (ImageView) findViewById(R.id.loc_btn_map_set_common4_img);
		iv_common5 = (ImageView) findViewById(R.id.loc_btn_map_set_common5_img);
		iv_common6 = (ImageView) findViewById(R.id.loc_btn_map_set_common6_img);

		// 初始化控件-名称的hash map
		addressButtonControls.put(btn_home, addressNames[0]);
		addressButtonControls.put(btn_company, addressNames[1]);
		addressButtonControls.put(btn_common1, addressNames[2]);
		addressButtonControls.put(btn_common2, addressNames[3]);
		addressButtonControls.put(btn_common3, addressNames[4]);
		addressButtonControls.put(btn_common4, addressNames[5]);
		addressButtonControls.put(btn_common5, addressNames[6]);
		addressButtonControls.put(btn_common6, addressNames[7]);
		// 初始化控件-名称的hash map
		addressTitleControls.put(tv_home, addressNames[0]);
		addressTitleControls.put(tv_company, addressNames[1]);
		addressTitleControls.put(tv_common1, addressNames[2]);
		addressTitleControls.put(tv_common2, addressNames[3]);
		addressTitleControls.put(tv_common3, addressNames[4]);
		addressTitleControls.put(tv_common4, addressNames[5]);
		addressTitleControls.put(tv_common5, addressNames[6]);
		addressTitleControls.put(tv_common6, addressNames[7]);
		// 名字对应的控件
		imageControls.put(addressNames[0], iv_home);
		imageControls.put(addressNames[1], iv_company);
		imageControls.put(addressNames[2], iv_common1);
		imageControls.put(addressNames[3], iv_common2);
		imageControls.put(addressNames[4], iv_common3);
		imageControls.put(addressNames[5], iv_common4);
		imageControls.put(addressNames[6], iv_common5);
		imageControls.put(addressNames[7], iv_common6);

		addressTextIds.put(tv_home, R.string.loc_btn_home);
		addressTextIds.put(tv_company, R.string.loc_btn_company);
		addressTextIds.put(tv_common1, R.string.loc_btn_common1);
		addressTextIds.put(tv_common2, R.string.loc_btn_common2);
		addressTextIds.put(tv_common3, R.string.loc_btn_common3);
		addressTextIds.put(tv_common4, R.string.loc_btn_common4);
		addressTextIds.put(tv_common5, R.string.loc_btn_common5);
		addressTextIds.put(tv_common6, R.string.loc_btn_common6);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	protected void onResume() {
		super.onResume();
		// 根据是否设置目的地，更改控件的颜色、状态
		feedSavedAddress();
	}

	/**
	 * The action when clicking the back button
	 * 
	 * @param view
	 *            the button of back
	 */
	public void back(View view) {
		// startActivity(new Intent(this, HomeActivity.class));
		finish();
	}

	/**
	 * The action when clicking the skip button
	 * 
	 * @param view
	 *            the button of back
	 */
	public void skip(View view) {
		Intent intent = new Intent(this, NavigatorPointsPickup.class);
		intent.putExtra("addressName", "");
		this.startActivityForResult(intent, 1);
		this.finish();
	}

	/**
	 * Send or locate
	 * 
	 * @param view
	 *            thew view
	 */
	public void naviOrLocate(View view) {
		TextView tv = (TextView) view;
		naviOrLocate(addressTitleControls.get(tv));
	}

	public void naviOrLocate(String name) {
		if (name != null && name.length() > 0) {
			final Destination d = Destination.getDestination(name);
			if (d != null) {
				// 导航至该地址
				String message = this
						.getString(R.string.loc_cofirm_navi_address)
						+ d.getAddress();
				new AlertDialog.Builder(this)
						.setTitle(R.string.loc_message)
						.setMessage(message)
						.setPositiveButton(this.getString(R.string.loc_okay),
								new OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										navi(d);
									}
								})
						.setNegativeButton(this.getString(R.string.loc_cancel),
								null).show();
			} else
				locate(name);
		}
	}

	/**
	 * Send or locate
	 * 
	 * @param view
	 *            thew view
	 */
	public void remove(View view) {
		Button button = (Button) view;
		final String addressName = addressButtonControls.get(button);
		if (addressName != null && addressName.length() > 0) {
			Destination d = Destination.getDestination(addressName);
			if (d != null) {
				new AlertDialog.Builder(this)
						.setTitle(R.string.loc_message)
						.setMessage(R.string.loc_cofirm_remove_address)
						.setPositiveButton(this.getString(R.string.loc_okay),
								new OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										remove(addressName);
									}
								})
						.setNegativeButton(this.getString(R.string.loc_cancel),
								null).show();

			} else {
				naviOrLocate(addressName);
			}
		}
	}

	/**
	 * Feed the saved address to the controls
	 */
	@SuppressWarnings("deprecation")
	private void feedSavedAddress() {
		// 设置常用地址栏的颜色
		for (View t : addressTitleControls.keySet()) {
			String addressName = addressTitleControls.get(t);
			TextView textView = (TextView) t;
			Destination destination = Destination.getDestination(addressName);
			Button btn = null;
			for (Entry<View, String> ent : addressButtonControls.entrySet()) {
				if (addressName.equals(ent.getValue())) {
					btn = (Button) (ent.getKey());
					break;
				}
			}
			// 如果没有设置常用地址，则设置为灰色
			if (destination == null) {
				int stringId = addressTextIds.get(textView);
				textView.setText(stringId);
				btn.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.gray_scale_normal_selector));
				btn.setText(getResources().getString(R.string.loc_setting));
				textView.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.gray_scale_normal_selector));
			} else {
				if (addressName.equals("home"))
					textView.setText(this.getString(R.string.loc_btn_home)
							+ "-" + destination.getAddress());
				else if (addressName.equals("company"))
					textView.setText(this.getString(R.string.loc_btn_company)
							+ "-" + destination.getAddress());
				else
					textView.setText(destination.getAddress());

				btn.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.general_yellow_btn_selector));
				btn.setText(getResources().getString(
						R.string.loc_setting_delete));
				textView.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.general_yellow_btn_selector));
			}
		}
	}

	/**
	 * Sending the address
	 * 
	 * @param destination
	 *            the destination to be send
	 */
	private void navi(Destination destination) {
		BDLocation currentLocation = IMDroid.getCurrentLocation();

		if (currentLocation == null) {
			Toast.makeText(this,
					this.getString(R.string.loc_error_no_gps_wait),
					Toast.LENGTH_LONG).show();
			return;
		}
		double mLat1 = currentLocation.getLatitude();
		double mLon1 = currentLocation.getLongitude();
		double mLat2 = destination.getLatitude();
		double mLon2 = destination.getLongitude();
		int lat = (int) (mLat1 * 1E6);
		int lon = (int) (mLon1 * 1E6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		lat = (int) (mLat2 * 1E6);
		lon = (int) (mLon2 * 1E6);
		GeoPoint pt2 = new GeoPoint(lat, lon);

		NaviPara para = new NaviPara();
		para.startPoint = pt1; // 起点坐标
		para.startName = this.getString(R.string.loc_map_loc);
		para.endPoint = pt2; // 终点坐标
		para.endName = destination.getAddress();

		try {
			BaiduMapNavigation.openBaiduMapNavi(para, this);
			this.finish();
		} catch (BaiduMapAppNotSupportNaviException e) {
			Toast.makeText(IMDroid.getContext(), e.getMessage(),
					Toast.LENGTH_LONG).show();
			// 在此处理异常
			e.printStackTrace();
		}
	}

	/**
	 * locate the address
	 * 
	 * @param addressName
	 *            the address name
	 */
	private void locate(String addressName) {
		Intent intent = new Intent(this, NavigatorPointsPickup.class);
		intent.putExtra("addressName", addressName);
		this.startActivityForResult(intent, 1);
		this.finish();
	}

	/**
	 * Remove the address name
	 * 
	 * @param addressName
	 *            remove the address
	 */
	private void remove(String addressName) {
		Destination.removeDestination(addressName);
		feedSavedAddress();
	}

}
